package com.geovis.emergency.spd.intercept;


import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.geovis.common.core.api.Result;
import com.geovis.emergency.spd.util.SignatureUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;


public class SignInterceptor implements HandlerInterceptor {


    private static final Logger log = LoggerFactory.getLogger(HandlerInterceptor.class);


    @Autowired
    private SignatureUtil signatureUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //需要验签
        String appId = request.getHeader("appId");
        String sign = request.getHeader("sign");
        String timestamp = request.getHeader("timestamp");
        Result result = new Result();
        if(StrUtil.isBlank(appId)||StrUtil.isBlank(timestamp)||StrUtil.isBlank(sign)){
            result.setCode(401);
            result.setMessage("无效签名，请检查后再试!");
            String json = JSONUtil.toJsonStr(result);
            returnJson(response,json);
            return false;
        }
        boolean verification = signatureUtil.verification(sign, timestamp, result);
        if (!verification){
            String json = JSONUtil.toJsonStr(result);
            returnJson(response,json);
            return false;
        }
        return true;
    }

    private void returnJson(HttpServletResponse response, String json){
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(json);

        } catch (IOException e) {
            log.error("response error",e);
        } finally {
            if (writer != null){
                writer.close();
            }

        }
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
